/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tp_imag.gui.area.selection;

import ij.ImagePlus;
import ij.gui.Roi;
import ij.io.FileInfo;
import ij.io.FileOpener;
import ij.io.FileSaver;
import ij.io.Opener;
import ij.plugin.DragAndDrop;
import ij.plugin.filter.PlugInFilter;
import ij.process.ColorProcessor;
import ij.process.ImageProcessor;

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Event;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;

import javax.swing.JPopupMenu;

import org.jdesktop.application.Action;

import tp_imag.gui.components.JImagePanel;
import tp_imag.model.ActualImage;



/**
 *
 * @author LRinaudo
 */
public class AreaSelectionPanel extends javax.swing.JPanel implements PlugInFilter, MouseListener {

    private BufferedImage loadImg;
    private ImagePlus newImage;
    private ImagePlus imageOriginal;
    int xInitial;
    int yInitial;
    int xDrag;
    int yDrag;
    int wNewImage;
    int hNewImage;
    private static String NEW_IMAGE_PATH = "areaSelection.jpg";
    JImagePanel panel = null;
    boolean dibujarArea = false;



    /** Creates new customizer AreaSelectionPanel */
    public AreaSelectionPanel() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the FormEditor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jOriginalPanel = new JImagePanel();
        jImageCroppedPanel = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jButton3 = new javax.swing.JButton();

        jButton1.setText("jButton1");

        setLayout(new java.awt.GridLayout(1, 0));

        jOriginalPanel.setToolTipText("Imagen Original");
        jOriginalPanel.setAlignmentX(0);
        jOriginalPanel.setAlignmentY(0);
        jOriginalPanel.setPreferredSize(new java.awt.Dimension(400, 260));
        jPanel2.add(jOriginalPanel);

        jImageCroppedPanel.setOpaque(false);
        jImageCroppedPanel.setPreferredSize(new java.awt.Dimension(400, 260));
        jPanel2.add(jImageCroppedPanel);

        jButton2.setAlignmentX(400.0F);
        jButton2.setAlignmentY(400.0F);
        jButton2.setLabel("Seleccionar sector");
        jButton2.setPreferredSize(new java.awt.Dimension(120, 25));
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	selectAreaAction(evt);
            }
        });

        jPanel1.add(jButton2);

        jPanel2.add(jPanel1);

        jButton3.setLabel("Borrar Selección");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	deleteSelectedAreaAction(evt);
            }
        });

        jPanel3.add(jButton3);

        jPanel2.add(jPanel3);

        add(jPanel2);
    }// </editor-fold>//GEN-END:initComponents


    private void loadImage() {
        try {
            loadImg = ActualImage.getInstance().getOriginal();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    private void showOriginalImg() {

        try {
            jOriginalPanel.setLocation(1, 1);

            int h = loadImg.getHeight();
            int w = loadImg.getWidth();

            jOriginalPanel.setSize(w, h);
            this.panel = new JImagePanel(loadImg, 0, 0, jOriginalPanel.getSize());
            /*double escalaX = jOriginalPanel.getSize().getHeight()/h;
            double escalaY = jOriginalPanel.getSize().getWidth()/w;

            if (escalaX < escalaY )
               this.escalaXY = escalaX;
            else
               this.escalaXY = escalaY;

            System.out.println("Escala AREA: "+this.escalaXY);
            */
            jOriginalPanel.setLayout(new BorderLayout());

            panel.setVisible(true);
            jOriginalPanel.add(panel);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void refreshScreen() {

    	loadImage();
        showOriginalImg();
    }

    public ImagePlus getNewImage (){
        Opener fileOpener = new Opener();
    	if (this.newImage == null){
        	this.imageOriginal = new ImagePlus();
        	this.imageOriginal.setImage(loadImg);
                this.newImage = this.imageOriginal;
        }


        ActualImage.getInstance().setOriginal(this.newImage.getBufferedImage());

        FileSaver fileSaver = new FileSaver(this.newImage);
    	fileSaver.saveAsJpeg(NEW_IMAGE_PATH);
        return this.newImage;
    }

    @Action
    public void selectAreaAction(java.awt.event.ActionEvent evt) {
    	this.imageOriginal = new ImagePlus();
    	this.imageOriginal.setImage(loadImg);
    	ColorProcessor imageProcessor = new ColorProcessor(loadImg);
    	this.setup(TOOL_TIP_TEXT_KEY, this.imageOriginal);
    	this.run(imageProcessor);
    }

    public void deleteSelectedAreaAction(java.awt.event.ActionEvent evt){
    	this.newImage = new ImagePlus();
    	jImageCroppedPanel.removeAll();
    	jImageCroppedPanel.updateUI();
    }

    // Start Mouse Listener
    public int setup(String arg, ImagePlus img) {
        return DOES_ALL+NO_CHANGES+ROI_REQUIRED;
    }

    public void run(ImageProcessor ip) {
    	this.jOriginalPanel.addMouseListener(this);
    }

	// method is called when mouse is clicked
    public void mouseClicked(MouseEvent e) {
    }

    public void mousePressed(MouseEvent e) {
    	this.xInitial = e.getX();
    	this.yInitial = e.getY();
        this.dibujarArea = true;
    }

    @Override
    public boolean mouseMove(Event evt, int x, int y) {
        this.xDrag = x;
        this.yDrag = y;
        this.repaint();

        return super.mouseMove(evt, x, y);
    }



    @Override
    public boolean mouseDrag(Event evt, int x, int y) {
        this.xDrag = x;
        this.yDrag = y;
        this.repaint();
        return super.mouseDrag(evt, x, y);
    }


    public void mouseReleased(MouseEvent e) {
        JImagePanel ip = (JImagePanel)e.getComponent();
    	int xFinal = e.getX();
    	int yFinal = e.getY();
    	if (xFinal == this.xInitial || yFinal == this.yInitial){
    	}
        System.out.println("Escala Area: " + this.panel.getEscalaXY());
        this.imageOriginal.setRoi((int)(this.xInitial / this.panel.getEscalaXY()) ,(int)( this.yInitial / this.panel.getEscalaXY()), (int)((xFinal - this.xInitial)/ this.panel.getEscalaXY()), (int) ((yFinal - this.yInitial) / this.panel.getEscalaXY()));

    	ImagePlus imageAux = this.imageOriginal;
    	this.newImage = new ImagePlus();
    	this.newImage.setProcessor(imageAux.getProcessor().crop());

    	displayNewImage();
    	FileSaver fileSaver = new FileSaver(this.newImage);

    	fileSaver.saveAsJpeg(NEW_IMAGE_PATH);
    	displayNewImage();
    }

    private void displayNewImage(){
    	int w = this.newImage.getWidth();
    	int h = this.newImage.getHeight();

    	jImageCroppedPanel.setSize(w,h);
    	JImagePanel panelImageCropped = new JImagePanel(this.newImage.getBufferedImage(), 0, 0, jImageCroppedPanel.getSize());
        jImageCroppedPanel.setLayout(new BorderLayout());
        panelImageCropped.setVisible(true);

        jImageCroppedPanel.add(panelImageCropped);
        jPanel2.updateUI();
    }

    @Override
    public void paint(Graphics g) {
        int x, y, w, h;
        if ( this.xInitial != 0) {
            if (this.xDrag - this.xInitial > 0){
                x = this.xInitial;
            }
            else{
                x = this.xDrag;
            }

            if (this.yDrag - this.yInitial > 0){
                y = this.yInitial;
            }
            else{
                y = this.yDrag;
            }
            w = Math.abs(this.xDrag - this.xInitial);
            h = Math.abs(this.yDrag - this.yInitial);
            g.drawRect( x, y, w, h);
        }
        super.paint(g);

    }

    public void mouseEntered(MouseEvent e) {}

    public void mouseExited(MouseEvent e) {}


    public ImagePlus getImage(){
    	return this.newImage;
    }
    // End Mouse Listener




    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JPanel jImageCroppedPanel;
    private javax.swing.JPanel jOriginalPanel;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    // End of variables declaration//GEN-END:variables

}
